package com.fy.login;

import com.fy.login.permissions.EventListenerPermission;

import java.util.*;

/**
 * 事件监听器工具类
 * @author zhufeifei 2022/8/7
 **/

public class EventListeners {
    private final Map<Type, List<IEventListener>> eventMap;
    private EventListeners() {
        this.eventMap = new EnumMap<>(Type.class);
    }
    public enum Type {
        LOGIN,LOGOUT
    }
    private static final EventListeners INSTANCE = new EventListeners();

    /**
     * 注册事件，以在事件更新时得到通知
     * @param type 事件类型
     * @param listener 监听器
     */
    public  static void register(Type type, IEventListener listener) {
        INSTANCE.eventMap.putIfAbsent(type,new ArrayList<>());
        INSTANCE.eventMap.get(type).add(listener);
    }


    public static EventListeners getInstance() {
        return INSTANCE;
    }

    /**
     * 返回事件视图
     * @param type 事件类型
     * @return {@literal List<EventListener>}
     */
    public List<IEventListener> getEvents(Type type) {
        return Collections.unmodifiableList(eventMap.getOrDefault(type, new ArrayList<>()));
    }

    /**
     * 获取事件列表（可修改）
     * @param type 事件类型
     * @return {@literal List<EventListener>}
     */
    public List<IEventListener> getRawEvents(Type type) {
        SecurityManager securityManager = System.getSecurityManager();
        if (securityManager != null) {
            securityManager.checkPermission(new EventListenerPermission("getRawEvents"));
        }
        return eventMap.getOrDefault(type, new ArrayList<>());
    }
}
